<template>
	<coreshop-page title="商家中心" mode="left">
		<view class="p-25">
			<view class="store-box" :style="{'top':`${statusBarHeight}px`}">
				<view class="store">
					<view class="name" @click="handleStoreList">
						<text class="tit">{{state.storeDetail?.storeName}}</text>
						<uv-icon name="arrow-down" color="#000" size="20"></uv-icon>
					</view>
					<view class="address">{{state.storeDetail?.address}}</view>
				</view>
				<view class="member" @click="handleRouteSwitchTab(RouteSwitchTabEnum.member)">
					<uv-icon name="arrow-leftward" color="#000" size="15"></uv-icon>
					<text class="tit">切换个人中心</text>
				</view>
			</view>

			<!-- 切换门店弹框 -->
			<uv-popup ref="storePopup" mode="bottom">
				<view class="layout-store-popup">
					<view class="store-popup-box">
						<view :class="['item',{'on':state.storeId == item.id}]" v-for="item in state.storeList"
							:key="item.id" @click="handleChangeStore(item)">
							<image class="img" :src="item.logoImage" mode=""></image>
							<view class="name-box">
								<view class="name">{{item.storeName}}</view>
								<view class="address">{{item.address}}</view>
							</view>
						</view>
					</view>
					<view class="pupup-btn">
						<view class="cancel" @click="handleCloseStorePopup">取消</view>
						<view class="all" v-if="state.isShopManager" @click="handleViewAllData">查看所有数据</view>
					</view>
				</view>
			</uv-popup>

			<view class="order-list">
				<view class="item"
					@click="handleRouteNavigateTo(`/pages/subpackage/merchant/takeDelivery/list/list?storeId=${state.storeId}`)">
					<view class="icon">
						<uv-icon name="order" color="#000" size="30"></uv-icon>
					</view>
					<view class="tit">提货单列表</view>
				</view>
				<view class="item"
					@click="handleRouteNavigateTo(`/pages/subpackage/merchant/takeDelivery/index/index`)">
					<view class="icon">
						<uv-icon name="empty-order" color="#000" size="30"></uv-icon>
					</view>
					<view class="tit">提货单核销</view>
				</view>
				<view class="item"
					@click="handleRouteNavigateTo(`/pages/subpackage/merchant/serviceVerification/list/list?storeId=${state.storeId}`)">
					<view class="icon">
						<uv-icon name="coupon" color="#000" size="30"></uv-icon>
					</view>
					<view class="tit">服务券列表</view>
				</view>
				<view class="item"
					@click="handleRouteNavigateTo(`/pages/subpackage/merchant/serviceVerification/index/index`)">
					<view class="icon">
						<uv-icon name="file-text" color="#000" size="30"></uv-icon>
					</view>
					<view class="tit">核验服务券</view>
				</view>
			</view>

			<view class="search-box">
				<uv-search v-model="state.keyWord" placeholder="请输订单号、收货人手机号、收货人姓名" :showAction="true" actionText="搜索"
					@custom="handleSearch"></uv-search>
			</view>

			<view class="tab-box">
				<view class="item" @click="handleOpenTimePicker">
					<view class="tit">{{state.dateText}}</view>
					<view class="icon">
						<uv-icon name="arrow-down-fill" color="#000" size="15"></uv-icon>
					</view>
				</view>
				<view class="item" @click="handleOpenStatusPicker">
					<view class="tit">{{state.statusText}}</view>
					<view class="icon">
						<uv-icon name="arrow-down-fill" color="#000" size="15"></uv-icon>
					</view>
				</view>
				<view class="item" @click="handleOpenReceiptTypePicker">
					<view class="tit">{{state.receiptTypeText}}</view>
					<view class="icon">
						<uv-icon name="arrow-down-fill" color="#000" size="15"></uv-icon>
					</view>
				</view>
			</view>

			<uv-picker ref="timePicker" keyName="label" :columns="state.timeList"
				@confirm="handleConfirmTime"></uv-picker>
			<uv-picker ref="statusPicker" keyName="label" :columns="state.statusList"
				@confirm="handleConfirmStatus"></uv-picker>
			<uv-picker ref="receiptTypePicker" keyName="label" :columns="state.receiptTypeList"
				@confirm="handleConfirmReceiptType"></uv-picker>

			<view class="total-box">
				<view class="order">
					订单量(单)：{{state.totalCount}}
				</view>
				<view class="price">
					交易额(单)：￥{{state.totalMoney}}
				</view>
			</view>

			<view class="list-box" v-if="state.list.length > 0">
				<view class="item-box" v-for="item in state.list" :key="item.id"
					@click="handleRouteNavigateTo(`/pages/subpackage/member/order/detail/detail?orderId=${item.orderId}&data=merchant`)">
					<view class="order-num">
						<text class="num">订单编号：{{ item.orderId }}</text>
						<text class="status">{{ item.shipStatusText }}</text>
						<uv-tags v-if="item.receiptType == OrderDistributionEnum.mailing" text="物流快递" plain size="mini"
							type="warning"></uv-tags>
						<uv-tags v-if="item.receiptType == OrderDistributionEnum.homeDelivery" text="同城配送" plain
							size="mini" type="warning"></uv-tags>
						<uv-tags v-if="item.receiptType == OrderDistributionEnum.selfDelivery" text="门店自提" plain
							size="mini" type="warning"></uv-tags>
					</view>
					<view class="goods-box">
						<view class="goods" v-for="itemChild in item.items" :key="itemChild.id">
							<coreshop-goods-card type="horizontal" imgHeight="140rpx" imgWidth="140rpx"
								:goodsData="hanldeCombinationGoodsData(itemChild)">
								<template #goodPrice>
									<view class="price-box">
										<view class="price">￥{{ itemChild.price }}</view>
										<view class="num">数量：{{ itemChild.nums }}</view>
									</view>
								</template>
							</coreshop-goods-card>
						</view>
					</view>
					<view class="peo-box">
						<view class="time">{{timeFormat(item.createTime, 'yyyy-mm-dd hh:MM:ss')}}</view>
						<view class="peo">{{ item.shipName }}【{{ item.shipMobile }}】</view>
					</view>
					<view class="order-status-box">
						<view>
							<uv-tags v-if="item.status == OrderStatusEnum.pending" text="订单正常" plain
								size="mini"></uv-tags>
							<uv-tags v-if="item.status == OrderStatusEnum.complete" text="订单完成" plain size="mini"
								type="success"></uv-tags>
							<uv-tags v-if="item.status == OrderStatusEnum.cancel" text="订单取消" plain size="mini"
								type="error"></uv-tags>
						</view>
						<view class="status">
							{{item.payStatusText}}
							<text v-if="item.paymentCodeText">【{{item.paymentCodeText}}】</text>
						</view>
						<view class="price">
							实付款：<text class="amount">￥{{item.payedAmount}}</text>
						</view>
					</view>
				</view>
				<view class="no-data" v-if="state.page === state.totalPages">没有更多了呀</view>
			</view>
			<view v-else>
				<coreshop-empty :mode="EmptyEnum.data" text="暂无数据"></coreshop-empty>
			</view>
		</view>
	</coreshop-page>

</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onReachBottom } from '@dcloudio/uni-app';
	import { queryStoreByUserId, queryIsClerk, queryOrderPageByMerchant, queryStoreListForUser } from '@/core/api';
	import type { Response } from '@/core/models';
	import { handleShowToast, handleRouteSwitchTab, handleRouteNavigateTo } from '@/core/utils';
	import { RouteSwitchTabEnum, EmptyEnum, OrderDistributionEnum, OrderStatusEnum } from '@/core/enum';
	import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import { useSystemInfo } from '@/core/hooks';

	interface QueryParams {
		storeId : number;
		isShopManager : boolean;
	}

	/** 获取自定义导航栏高度 */
	const { statusBarHeight } = useSystemInfo();
	const storePopup = ref();
	const timePicker = ref();
	const statusPicker = ref();
	const receiptTypePicker = ref();

	const state = reactive<{
		storeId : number;
		storeDetail : any;
		page : number;
		totalPages : number;
		list : Array<any>;
		dateText : string;
		dateType : string;
		receiptTypeText : string;
		receiptType : string;
		statusText : string;
		status : string;
		totalCount : number;
		totalMoney : number;
		latitude : number;
		longitude : number;
		keyWord : string;
		storeList : Array<any>;
		timeList : Array<any>;
		statusList : Array<any>;
		receiptTypeList : Array<any>;
		isShopManager : boolean;
	}>({
		storeId: 0,
		storeDetail: {},
		page: 1,
		totalPages: 1,
		list: [],
		dateText: "全部",
		dateType: 'all',
		receiptTypeText: "全部",
		receiptType: '0',
		statusText: "全部",
		status: '0',
		totalCount: 0,
		totalMoney: 0,
		latitude: 0,
		longitude: 0,
		keyWord: "",
		storeList: [],
		timeList: [[
			{ 'label': '全部', 'id': 'all' }, { 'label': '今日', 'id': 'today' }, { 'label': '昨日', 'id': 'yesterday' },
			{ 'label': '本周', 'id': 'week' }, { 'label': '本月', 'id': 'month' }, { 'label': '自定义', 'id': 'custom' },
		]],
		statusList: [[
			{ 'label': '全部', 'id': '0' }, { 'label': '待付款', 'id': '1' }, { 'label': '待发货', 'id': '2' },
			{ 'label': '待收货', 'id': '3' }, { 'label': '待评价', 'id': '4' }, { 'label': '已完成', 'id': '6' }, { 'label': '已取消', 'id': '7' }
		]],
		receiptTypeList: [[
			{ 'label': '全部', 'id': '0' }, { 'label': '物流快递', 'id': '1' }, { 'label': '同城配送', 'id': '2' }, { 'label': '门店自提', 'id': '3' },
		]],
		isShopManager: false,
	});

	onLoad((query : QueryParams) => {
		state.storeId = query?.storeId;
		getStoreByUserId();
		getIsClerk();
		getOrderPageByMerchant();
	});

	onReachBottom(() => {
		if (state.totalPages > state.page) {
			state.page++;
			getOrderPageByMerchant();
		}
	});

	/** 查看是否是店员*/
	const getIsClerk = async () => {
		const isClerk : Response<any> = await queryIsClerk();
		if (isClerk.status) {
			state.isShopManager = isClerk.data?.isShopManager;
		}
	}

	/** 获取门店详情 */
	const getStoreByUserId = async () => {
		const storeByUser : Response<any> = await queryStoreByUserId({
			id: state.storeId
		});
		if (storeByUser.status) {
			state.storeDetail = storeByUser?.data;
		} else {
			handleShowToast(storeByUser.msg)
		}
	}

	/** 获取门店订单列表 */
	const getOrderPageByMerchant = async () => {
		const merchant : Response<any> = await queryOrderPageByMerchant({
			dateType: state.dateType,
			date: [],
			status: state.status,
			receiptType: state.receiptType,
			page: state.page,
			limit: 10,
			storeId: state.storeId
		});
		if (merchant.status) {
			state.totalPages = merchant.data?.totalPages;
			state.totalCount = merchant.data?.totalCount;
			state.totalMoney = merchant.data?.totalMoney;
			state.list = state.list.concat(merchant.data?.pages);
		} else {
			handleShowToast(merchant.msg)
		}
	}

	/** 组合商品数据传入组件 */
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			id: item.id,
			image: item.imageUrl,
			name: item.name,
			brief: item.addon,
		}
	}

	/** 获取门店列表 */
	const handleStoreList = () => {
		// #ifdef MP-WEIXIN
		wx.getFuzzyLocation({
			type: 'wgs84',
			success(res : any) {
				state.latitude = res.latitude
				state.longitude = res.longitude
				//console.log('当前位置的经度1：' + res);
			},
			fail: function () {
				handleShowToast("获取您的经纬度坐标失败")
			},
			complete: function () {
				if (!state.longitude || !state.latitude) {
					state.longitude = 0;
					state.latitude = 0;
				}
				getStoreList();
			}
		})
		// #endif
		// #ifndef MP-WEIXIN
		uni.getLocation({
			type: 'wgs84',
			success: function (res) {
				state.longitude = res.longitude;
				state.latitude = res.latitude;
			},
			fail: function () {
				state.latitude = 0;
				state.longitude = 0;
				handleShowToast("获取您的经纬度坐标失败")
			},
			complete: function () {
				if (!state.longitude || !state.latitude) {
					state.longitude = 0;
					state.latitude = 0;
				}
				getStoreList();
			}
		});
		// #endif
	}

	/** 搜索 */
	const handleSearch = () => {
		if (!state.keyWord) {
			handleShowToast("请输订单号、收货人手机号、收货人姓名")
			return;
		}
		handleRouteNavigateTo(`/pages/subpackage/merchant/search/search?keyWord=${state.keyWord}&storeId=${state.storeId}`)
	}

	const getStoreList = async () => {
		const storeList : Response<any> = await queryStoreListForUser({
			'longitude': state.longitude,
			'latitude': state.latitude,
		});
		if (storeList.status) {
			storePopup.value.open();
			state.storeList = storeList?.data;
		} else {
			handleShowToast(storeList.msg)
		}
	}

	/** 查看所有数据 */
	const handleViewAllData = () => {
		state.storeId = 0;
		getStoreByUserId();
		handleCloseStorePopup();
		handleReset();
	}

	/** 切换门店 */
	const handleChangeStore = (item : any) => {
		if (state.storeId != item.id) {
			state.storeId = item.id;
			state.storeDetail = item;
			handleCloseStorePopup();
			handleReset();
		}
	}

	const handleReset = () => {
		state.page = 1;
		state.list = [];
		getOrderPageByMerchant();
	}

	/** 关闭门店弹框 */
	const handleCloseStorePopup = () => {
		storePopup.value.close();
	}

	/** 时间选择 */
	const handleOpenTimePicker = () => {
		timePicker.value.open();
	}
	const handleConfirmTime = ({ value } : any) => {
		state.dateText = value[0].label;
		state.dateType = value[0].id;
		handleReset();
	}

	/** 订单状态选择 */
	const handleOpenStatusPicker = () => {
		statusPicker.value.open();
	}
	const handleConfirmStatus = ({ value } : any) => {
		state.statusText = value[0].label;
		state.status = value[0].id;
		handleReset();
	}

	/** 快递方式选择 */
	const handleOpenReceiptTypePicker = () => {
		receiptTypePicker.value.open();
	}
	const handleConfirmReceiptType = ({ value } : any) => {
		state.receiptTypeText = value[0].label;
		state.receiptType = value[0].id;
		handleReset();
	}
</script>

<style scoped lang="scss">
	@import './index.scss';
</style>